package com.wn.sk.product.service.impl;

import com.wn.common.api.Result;
import com.wn.sk.Asserts;
import com.wn.sk.feign.dto.OrderPayDto;
import com.wn.sk.feign.vo.OrderVo;
import com.wn.sk.order.client.OrderFeignClient;
import com.wn.sk.product.entity.PromotionSeckill;
import com.wn.sk.product.entity.vo.PaymentVo;
import com.wn.sk.product.mapper.PromotionSeckillMapper;
import com.wn.sk.product.mqwork.OrderMQProduct;
import com.wn.sk.product.service.IPromotionSeckillService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 秒杀活动表 服务实现类
 * </p>
 *
 * @author yellow docker
 * @since 2022-11-07
 */
@Service
public class PromotionSeckillServiceImpl extends ServiceImpl<PromotionSeckillMapper, PromotionSeckill> implements IPromotionSeckillService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private OrderMQProduct orderMQProduct;

    @Autowired
    private PromotionSeckillMapper promotionSeckillMapper;

    /**
     *  确认订单
     *
     *  1、你传入 订单支付对象     返回一个订单付款对象
     *
     *
     * @param orderPayDto
     * @param userId
     * @return
     */
    @Override
    public Result<PaymentVo> confirmeOrder(OrderPayDto orderPayDto, String userId) {

        //01订单支付对象    orderPayDto
        String orderSn = orderPayDto.getOrderSn();
        Integer promotionId = orderPayDto.getPromotionId();

        //需要远程查询订单的 价格
        //远程查询订单的信息
        OrderVo orderVo = orderFeignClient.findOrderByOrderSn(orderSn).getData();

        //判断订单状态是否 合法
        if (orderVo.getStatus().equals("5")){
            Asserts.failed("订单以失效");
        }
        if (orderVo.getStatus().equals("4")){
            Asserts.failed("订单以关闭");
        }

        //付款计时发送到 mq中
        // 把订单 orderSn、productId 发送到 MQ
        orderMQProduct.sendMsg(orderPayDto);

        PaymentVo paymentVo = PaymentVo.builder()
                .orderSn(orderSn) //订单编号
                .promotionId(promotionId) //秒杀活动id
                .totalAmount(orderVo.getTotalAmount())
                .userId(userId).build();

        return Result.ok(paymentVo);
    }

    /**
     * 订单付款
     * @param orderPayDto
     * @return
     */
    @Override
    public Result<String> payOrder(OrderPayDto orderPayDto) {
        //01 修改 了订单状态
        Result<String> result = orderFeignClient.updateOrder(orderPayDto);
        //02 库存减少
        if (result.getData().equals("success")){
            //成功 减库存  减秒杀商品的 db中的库存
           int row = promotionSeckillMapper.updateStock(orderPayDto.getPromotionId());
           return  row > 0 ? Result.ok("支付成功"): Result.fail("支付失败");
        }
        return Result.fail("支付失败");
    }

}
